<template>
  <div>
    <el-button-group>
      <el-button type="primary" :icon="CirclePlus" v-auth="'CreateUser'" @click="formVisible = true"
        >新建用户</el-button
      >
      <el-button type="danger" :icon="Remove" v-auth="'DeleteUser'" @click="handleDeleteList">删除用户</el-button>
    </el-button-group>
    <x-table
      ref="refTable"
      name="用户"
      :columns="userColumns"
      :init-sort="{ userCode: 'ascending' }"
      :data="tableData.resp.list"
      :total="tableData.resp.total"
      :loading="tableData.loading"
      @query="handleQuery"
    >
      <template #column-userStatus="scope">
        <div v-if="!hasFuncKey('Enabled/Disabled')">
          <el-tag v-if="scope.data === 0" type="info">禁用</el-tag>
          <template v-else>启用</template>
        </div>
        <el-switch
          v-else
          :model-value="statusData[scope.row.userId]"
          inline-prompt
          :active-value="1"
          :inactive-value="0"
          active-text="启用"
          inactive-text="禁用"
          inactive-color="#909399"
          @change="handleChange($event, scope.row)"
        />
      </template>
      <template #column-opera="scope">
        <div class="opera-col">
          <el-link
            v-if="hasFuncKey('EditPwd')"
            plain
            type="primary"
            :underline="false"
            :icon="Edit"
            @click="handleOpenEditPwd(scope.row)"
          >
            <span class="text">修改密码</span>
          </el-link>
          <el-link
            v-if="hasFuncKey('EditUser')"
            plain
            type="primary"
            :underline="false"
            :icon="Edit"
            @click="handleOpenEditForm(scope.row)"
          >
            <span class="text">修改</span>
          </el-link>
          <el-popconfirm
            v-if="hasFuncKey('DeleteUser')"
            :title="`确定删除[ ${scope.row.userName} ]吗?`"
            @confirm="handleDelete([scope.row.userId], scope.row.userName)"
          >
            <template #reference>
              <el-link plain type="danger" :underline="false" :icon="Remove">
                <span class="text">删除</span>
              </el-link>
            </template>
          </el-popconfirm>
        </div>
      </template>
    </x-table>
    <Form ref="refForm" v-model:visible="formVisible" @success="handleFormSuccess" />
    <FormPwd ref="refFormPwd" v-model:visible="formPwdVisible" />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElPopconfirm, ElTag, ElSwitch } from 'element-plus'
import { CirclePlus, Remove, Edit } from '@element-plus/icons-vue'
import { confirm } from '@/utils'
import { useColumn } from '@/hooks/column'
import { useAuth } from '@/hooks/auth'
import { userApi } from '@/api/modules/system/user'
import type { User } from '@/api/modules/system/user'
import { useUser } from './hook'
import Form from './Form.vue'
import FormPwd from './FormPwd.vue'

// 获取权限钩子，用于判断column中的修改和删除按钮 是否显示
const { hasFuncKey, hasFuncKeysCount } = useAuth()

const { refTable, tableData, statusData, handleQuery, columns } = useUser()
const { columnOpera } = useColumn()
const hasCount = hasFuncKeysCount(['EditPwd', 'EditUser', 'DeleteUser'])
const userColumns = columns.concat([{ ...columnOpera, width: 75 * hasCount, isCreate: hasCount > 0 }] as any[])

const refForm = ref()
const formVisible = ref(false)

// 打开修改的窗口
const handleOpenEditForm = (data: User) => {
  formVisible.value = true
  refForm.value.setFormData(data)
}

// 新建或修改成功后的回调函数，此刷新方法必须写在table组件所在的类文件中，否则执行其方法会出错
const handleFormSuccess = () => {
  refTable.value.refresh()
}

// 删除多个
const handleDeleteList = () => {
  if (refTable.value.selection.length === 0) {
    ElMessage.warning({ message: '请至少勾选列表中的一条数据' })
    return
  }
  confirm('确定要删除用户吗?', () => {
    handleDelete(
      refTable.value.selection.map((item: User) => {
        return item.userId
      })
    )
  })
}
// 执行删除操作
const handleDelete = (ids: string[], name = '') => {
  // log.action('删除用户')
  userApi.delete(ids).then(resp => {
    if (resp.success) {
      refTable.value.refresh()
      ElMessage.success(name ? `用户[ ${name} ]已删除` : `${ids.length} 个用户已删除`)
    } else {
      ElMessage.error(resp.message)
    }
  })
}

const handleChange = (val: any, u: User) => {
  const originVal = statusData[u.userId]
  if (originVal === undefined || !u.userId) return
  statusData[u.userId] = val
  // log.action('激活/禁用用户')
  userApi.updateUserStatus({ userId: u.userId, userStatus: val } as User).then(resp => {
    if (resp.success) {
      u.userStatus = val
      ElMessage.success(`用户[ ${u.userName} ]状态已更新`)
    } else {
      statusData[u.userId] = originVal
      ElMessage.error(resp.message)
    }
  })
}

const refFormPwd = ref()
const formPwdVisible = ref(false)
const handleOpenEditPwd = (data: User) => {
  formPwdVisible.value = true
  refFormPwd.value.setFormData(data)
}
</script>

<style lang="scss" scoped>
.opera-col {
  display: flex;
  justify-content: space-around;
  .text {
    padding: 0 2px;
  }
}
:deep(.el-switch__core) {
  width: 50px;
}
</style>
